/**
 * 选择弹窗：选择结果回显至展示区及弹窗内部
 * @params propItem
 * @returns object
 */
import { formatAll } from '@/filters';

export default {
  props: {
    propItem: Object,
  },
  data() {
    return {
      innerValue: '',
      showPicker: false,
      index: 0,
      ...this.propItem,
    };
  },
  mounted() {
    this.innerValue = formatAll(this.value);
    this.index = this.columns.findIndex((item) => item.code === this.value);
  },
  updated() {
    // 选择医院时是根据地区调用接口返回医院信息，切换地区时需清空已选值
    if (!this.columns.length) {
      this.innerValue = '';
    }
  },
  methods: {
    preHandle() {
      if (this.disabled) {
        this.$toast(this.disabledText);
        return;
      }
      this.showPicker = true;
    },
    onConfirm(item, index) {
      let value = item.code;
      if (this.code === 'department') {
        this.innerValue = item.join('/');
        const choseArray = item.filter((val) => val);
        const choseObj = this.columns[index[choseArray.length - 1]];
        value = {
          departmentId: choseObj.id,
          departmentName: choseObj.name,
        };
      } else {
        this.innerValue = item.label;
      }
      this.$emit('accept', { value, code: this.code });
      this.showPicker = false;
    },
  },
  render() {
    return (
      <div>
        <van-field
          readonly
          clickable
          is-link
          disabled={this.disabled}
          value={this.innerValue}
          label={this.label}
          placeholder={this.placeholder}
          onClick={this.preHandle}
          rules={this.rules}
        />
        <van-popup v-model={this.showPicker} position="bottom">
          <van-picker
            value-key="label"
            show-toolbar
            default-index={this.index}
            columns={this.columns}
            onConfirm={this.onConfirm}
            onCancel={() => (this.showPicker = false)}
          />
        </van-popup>
      </div>
    );
  },
};
